package com.codechuan.didi_hack.utils;

import com.quickjs.JSContext;
import com.quickjs.QuickJS;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo {

    /**
     * @Deprecated 生成指定位数的字符串
     * @param count 数量
     * @return 返回字符串
     */
    public static String getRandomAlphanumeric(int count) {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < count; i++) {
            boolean isUpperCase = random.nextBoolean(); // 50% chance of upper case
            char c = isUpperCase ? (char) (random.nextInt(26) + 'A') // Upper case
                    : (char) (random.nextInt(26) + 'a'); // Lower case
            builder.append(c);
        }
        return builder.toString();
    }

    /**
     * @param text 文本
     * @Deprecated 获取md5
     */
    public static String getMD5(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(text.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @param functionDefinition 函数名称
     * @return
     * @Deprecated js算法表达式替换
     */
    public static String extractFunctionName(String functionDefinition) {
        // 正则表达式匹配函数名
        Pattern pattern = Pattern.compile("function\\s+(\\w+)");
        Matcher matcher = pattern.matcher(functionDefinition);

        if (matcher.find()) {
            return matcher.group(1);
        }
        return null; // 如果没有匹配到，则返回null
    }

    /**
     * @return
     * @Deprecated 执行js函数运算
     */
    public static String executeJs(String func_def, String func, String args) {
        QuickJS quickJS = QuickJS.createRuntime();
        JSContext context = quickJS.createContext();
        context.executeScript(func_def, "file.js");
        String result = context.executeStringScript(func + "(" + args + ")", "file.js");
        context.close();
        quickJS.close();
        return result;
    }

    /**
     * @param input 需要获取的文本
     * @return 返回取出的数据
     * @Deprecated 获取{}中间的所有内容
     */
    public static String extractContent(String input) {
        int start = input.indexOf("{");
        int end = input.indexOf("}");
        if (start != -1 && end != -1 && start < end) {
            return input.substring(start + 1, end);
        }
        return null;
    }
}
